package com.supplychainapi.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;


public class CommonUtil {

    private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);

    public static String getShopType(Integer fiShopKind) {
        String shopType = "";
        switch (fiShopKind) {
            case 0:
                shopType  = "A";
                break;
            case 1:
                shopType  = "B";
                break;
            case 3:
                shopType  = "C";
                break;
            case 6:
                shopType  = "F";
                break;
            case 7:
                shopType  = "D";
                break;
            case 9:
                shopType  = "E";
                break;
        }

        return shopType;
    }

    public static String getToken(String token, String type) {
        token =  MD5Utils.MD5Encode(token);
        if (type.equals("PHONE")){
            return Constants.SCM_PHONE_PREFIX + token;
        }
        return Constants.SCM_PHONE_PREFIX + token;

    }

    /**
     * 直接通过java返回js
     * @param response
     * @param responseStr
     * @return
     */
    public static void sendResponseJs(HttpServletResponse response, String responseStr) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader( "Pragma", "no-cache" );
        response.setDateHeader("Expires", 0);
        response.addHeader( "Cache-Control", "no-cache" );
        response.setHeader("Content-type", "application/x-javascript;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(responseStr);
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }

    /**
     * 获取当前请求的domain
     * @param request
     * @return
     */
    public static String getDomain(HttpServletRequest request) {
        URL url = null;
        try {
            StringBuffer rUrl = request.getRequestURL();
            url = new URL(rUrl.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        if (url == null) {
            return "";
        }
        return url.getHost();
    }
}
